<template>
  <div class="content">
    <el-card>
      <!-- 头部添加按钮和搜索框 -->
      <div class="main-header">
        <el-row type="flex">
          <el-col>
            <el-button
              type="primary"
              @click="isShowDialog = true"
            >添加分类</el-button>
          </el-col>
          <el-col>
            <el-row type="flex" justify="end">
              <el-input v-model="serachContent" placeholder="请输入搜索内容" />
              <el-button icon="el-icon-search" plain type="info" @click="searchFn" />
            </el-row>
          </el-col>
        </el-row>
      </div>
      <!-- 线 -->
      <el-divider />
      <!-- 表单 -->
      <el-table style="width: 100%" border :data="cateList">
        <el-table-column label="图片">
          <template #default="{row}">
            <img :src="row.image" alt="" style="width:200px">
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" />
        <el-table-column label="介绍" prop="desc" />
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button
              size="mini"
              type="primary"
              @click="editFn(row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="delFn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 线 -->
      <el-divider />
      <!-- 分页组件 -->
      <el-row type="flex" justify="center">
        <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSize" :current-page="page" @current-change="currentChange" />
      </el-row>
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      :title="formData.id?'编辑分类':'添加分类'"
      :visible="isShowDialog"
      :close-on-click-modal="false"
      @close="btnCancel"
    >
      <el-form ref="formData" label-width="100px" :model="formData" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="formData.desc" type="textarea" resize="none" />
        </el-form-item>
        <el-form-item label="封面">
          <ImgUpload ref="ImgUpload" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="btnOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addCategoty, delCategoty, editCategoty, getCategotyCount, getCategotyDetail, getcategotyList } from '@/api/Category'
import ImgUpload from '@/components/ImgUpload'
export default {
  components: { ImgUpload },
  data() {
    return {
      isDisabled: false,
      serachContent: '', // 搜索框内容
      searchData: '', // 用于搜索的内容
      isShowDialog: false, // 弹窗
      total: 0, // 数据总数
      // 弹窗表单数据
      formData: {
        title: '',
        desc: '',
        image: '',
        created_by: new Date(),
        updated_by: new Date()
      },
      // 弹窗输入框规则
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      },
      // 分类列表
      cateList: [],
      // 分页配置
      page: 1, // 页数
      pageSize: 2// 每页显示个数
    }
  },
  created() {
    this.getcateList()
  },
  methods: {
    // 获取分类列表_contains
    async getcateList(searchData) {
      // _limit为显示列表个数
      // _start为完整的列表中的某个下标开始显示，_start为下标
      // 获取当前页显示的列表，需要让完整列表的下标_start=（当前页-1）*每页显示的数据个数，
      // 以本页面来说，即第一页从完整列表[0]开始显示，第二页从完整列表[2]开始显示，第三页为完整列表[4]....
      const res = await getcategotyList({ title_contains: searchData, _limit: this.pageSize, _start: (this.page - 1) * this.pageSize })
      const Total = await getCategotyCount({ title_contains: searchData })
      this.cateList = res.data
      this.total = Total.data
    },
    // 搜索按钮
    searchFn() {
      this.searchData = this.serachContent
      this.page = 1
      this.getcateList(this.searchData)
    },
    // 编辑按钮
    async editFn(id) {
      this.isShowDialog = true
      const res = await getCategotyDetail(id)
      this.formData = res.data
      this.$refs.ImgUpload.fileList.push({ url: this.formData.image })
    },
    // 删除按钮
    async delFn(id) {
      await this.$confirm('确定要删除？')
      await delCategoty(id)
      // 安全判定：删除最后一页最后一个时跳到上一页
      if (this.cateList.length === 1 && this.page > 1) {
        this.page--
      }
      this.$message.success('删除成功')
      this.getcateList()
    },
    // 关闭弹窗
    btnCancel() {
      this.isShowDialog = false
      this.$refs.ImgUpload.fileList = []
      this.formData = {
        title: '',
        desc: '',
        image: '',
        created_by: '',
        updated_by: ''
      }
      this.$refs.formData.resetFields()
    },
    // 弹窗确定键
    async btnOk() {
      await this.$refs.formData.validate()
      this.isDisabled = true
      // 后台没图片会报400，所以需要判定有没有图片
      const fileList = this.$refs.ImgUpload.fileList
      if (fileList[0].status !== 'success') {
        this.$message.warning('图片还没上传完')
        setTimeout(() => {
          this.isDisabled = false
        }, 1000)
        return
      }
      this.formData.image = fileList[0].url
      if (this.formData.id) {
        // 编辑分类
        await editCategoty(this.formData)
      } else {
        // 新增分类
        await addCategoty(this.formData)
      }
      this.$message.success('操作成功')
      this.getcateList()
      this.isShowDialog = false
      setTimeout(() => {
        this.isDisabled = false
      }, 1000)
    },
    // 翻页
    currentChange(val) {
      this.page = val
      this.getcateList(this.searchData)
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  margin: 20px;
}
</style>
